<template>
  <div v-html="result"> </div>
</template>

<script setup name="MarkdownVue">
import { ref, watchEffect, watch, nextTick } from 'vue';
import { Marked } from 'marked';
// import { markedHighlight } from 'marked-highlight';
import hljs from 'highlight.js';

// import 'highlight.js/styles/github.css';
// import 'highlight.js/styles/arta.css'
// import 'highlight.js/styles/github-dark.css'
// import 'highlight.js/styles/atom-one-dark.css'

const props = defineProps({
  source: {
    type: String,
    default: '',
  },
  codeTheme: {
    type: String,
    default: 'github',
  },
});

const result = ref('');

const marked = new Marked({
  async: true,
  pedantic: false,
  gfm: true,
});

// 自定义渲染器
const renderer = new marked.Renderer();

// 重写代码块的渲染方法
// renderer.code = (code, language) => {
//   console.log('renderer.code', code)
//   console.log('renderer.lang', language)
//   const validLanguage = hljs.getLanguage(language) ? language : 'plaintext';
//   const highlighted = hljs.highlight(code, { language: validLanguage }).value;
//   // return `<pre class="hljs ${codeTheme}"><code class="hljs ${validLanguage}">${highlighted}</code></pre>`;
//   return highlighted;
// };

// const __code__ = renderer.code;
renderer.code = function (token) {
  // return __code__.apply(this, arguments);

  const text = this.parser.parseInline(token);

  if (token.lang === 'js') {
    console.log('token.lang:', token.lang);
    console.log('token:', token);
    console.log('text:', text);
  }

  const lang = hljs.getLanguage(token.lang) ? token.lang : 'plaintext';
  const highlighted = hljs.highlight(token.text, { language: lang }).value;

  return `<pre class="code-theme--${props.codeTheme}"><code class="hljs language-${lang}">${highlighted}</code></pre>`;
};

marked.setOptions({
  renderer,
});

// const marked = new Marked(
//   markedHighlight({
//     emptyLangClass: 'hljs',
//     langPrefix: 'hljs language-',
//     highlight(code, lang, info) {
//       const language = hljs.getLanguage(lang) ? lang : 'plaintext';
//       return hljs.highlight(code, { language }).value;
//     },
//   }),
// );

watch(() => props.codeTheme, async () => {
  // result.value = '';
  // nextTick(async () => {
  // })
  result.value = await marked.parse(props.source);
})

watchEffect(async () => {
  result.value = await marked.parse(props.source);
});
</script>
